import * as echarts from 'echarts';
import { isNil } from "lodash-es";
import React from "react";
import { IProvinceGDP } from "../../core/interface";

export interface IProps {
    year: number;
    currentProvince: string;
    currentData: IProvinceGDP;
}

/** 饼状图 */
const PieChart: React.FC<IProps> = (props) => {
    const { year, currentProvince, currentData } = props;
    const containerRef = React.useRef<HTMLDivElement>(null);
    const chartRef = React.useRef<echarts.ECharts>(null);

    const renderChart = () => {
        if (isNil(containerRef.current) || isNil(currentData)) return;
        const { width, height } = containerRef.current.getBoundingClientRect();
        const chartWidth = width;
        const chartHeight = height;
        const option = {
            title: {
                show: true,
                text: `${currentProvince}•${year}年GDP分布`,
                textAlign: 'auto',
            },
            tooltip: {
                trigger: 'item'
            },
            legend: {
                bottom: '5%',
                left: 'center'
            },
            series: [
                {
                    name: `${currentProvince}•${year}年GDP分布`,
                    type: 'pie',
                    radius: ['40%', '70%'],
                    avoidLabelOverlap: false,
                    label: {
                        show: false,
                        position: 'center'
                    },
                    emphasis: {
                        label: {
                            show: true,
                            fontSize: 40,
                            fontWeight: 'bold'
                        }
                    },
                    labelLine: {
                        show: false
                    },
                    data: [
                        { value: currentData.gdp1, name: '第一产业' },
                        { value: currentData.gdp2, name: '第二产业' },
                        { value: currentData.gdp3, name: '第三产业' },
                    ]
                }
            ]
        };
        if (chartRef.current) {
            // update
            chartRef.current.setOption(option);
        } else {
            const chart = echarts.init(containerRef.current, undefined, {
                height: chartHeight,
                width: chartWidth,
            });

            chart.setOption(option);
            chartRef.current = chart;
        }


    };

    React.useEffect(() => {
        renderChart();
    }, [currentData]);

    return (
        <div className="pie-chart-contaienr" ref={containerRef} style={{
            width: '100%',
            height: '50%',
            display: 'inline-block',
            verticalAlign: 'top',
            borderBottom: '1px solid #C4C6CF',
        }}>

        </div>
    );
};

export default PieChart;